<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="经销商编码">
              <a-input placeholder="请输入经销商编码" v-model="queryParam.storeId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="经销商名称">
              <a-input placeholder="请输入经销商名称" v-model="queryParam.storeName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="跟单员">
              <a-input placeholder="请输入跟单员" v-model="queryParam.saleRealName"></a-input>
            </a-form-item>
          </a-col>
<!--          <a-col :md="4" :sm="8">-->
<!--            <a-form-item label="状态">-->
<!--              <j-dict-select-tag v-model="queryParam.auditStatus" placeholder="请选择审核状态"-->
<!--                                 dictCode="discountApproveStatus"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md="6" :sm="8">-->
<!--            <a-form-item label="时间">-->
<!--              <a-range-picker format="YYYY-MM-DD HH:mm:ss"-->
<!--                              :style="{width: '277px'}"-->
<!--                              :show-time="{-->
<!--                                hideDisabledOptions: true,-->
<!--                                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],-->
<!--                              }"-->
<!--                              :placeholder="['开始时间', '结束时间']"-->
<!--                              @change="onCreateTimeChange"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleSync" type="primary" icon="import">手工同步</a-button>
<!--      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>-->
<!--      <a-button type="primary" icon="download" @click="handleExportXls('经销商折扣表')">导出</a-button>-->
<!--      <a-button type="primary" icon="download" @click="downloadTemplate('折扣导入模版.xlsx')">下载模板</a-button>-->
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"-->
<!--                @change="handleImportExcel">-->
<!--        <a-button type="primary" icon="import">导入</a-button>-->
<!--      </a-upload>-->
<!--      <a-space v-if="selectedRowKeys.length > 0">-->
<!--        <a-button @click="handleApprove" type="primary" icon="plus">批量审核</a-button>-->
<!--        <a-button @click="handleEdit" type="primary" icon="plus">批量编辑</a-button>-->
<!--      </a-space>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        <span>已选择</span>
        <a style="font-weight: 600">
          {{ selectedRowKeys.length }}
        </a>
        <span>项</span>
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type:type,getCheckboxProps: getCheckboxProps}"
        @change="handleTableChange"
        :customRow="clickThenCheck">
      </a-table>
    </div>
    <!-- table区域-end -->

    <a-tabs defaultActiveKey="1">
    </a-tabs>

    <!-- 表单区域 -->
    <stmDealerDiscount-modal ref="modalForm" @ok="modalFormOk"/>
    <stmDealerInfoDiscountApprove ref="StmDealerInfoDiscountApprove"  @ok="modalFormOk"></stmDealerInfoDiscountApprove>
  </a-card>
</template>

<script>
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import StmDealerDiscountModal from './modules/StmDealerDiscountModal'
import {deleteAction, getAction} from '@/api/manage'
import JDate from '@/components/jeecg/JDate'
import moment from "moment"
import StmDealerInfoDiscountApprove from './modules/StmDealerInfoDiscountApprove'
import {downFile} from "../../api/manage";

export default {
  name: "StmDealerDiscountList",
  mixins: [JeecgListMixin],
  components: {
    StmDealerDiscountModal,
    JDate,
    StmDealerInfoDiscountApprove
  },
  data() {
    return {
      refKeys: [],
      description: '经销商折扣表管理页面',
      // 表头
      columns: [

        {
          title: '经销商编码',
          align: "center",
          dataIndex: 'storeId'
        },
        {
          title: '经销商名称',
          align: "center",
          dataIndex: 'storeName'
        },
        {
          title: '组织',
          align: "center",
          dataIndex: 'companyCode'
        },
        {
          title: '渠道',
          align: "center",
          dataIndex: 'channelName'
        },
        {
          title: '货物优惠可用额度',
          align: "center",
          dataIndex: 'productRemainAmount'
        },
        {
          title: '促销优惠可用额度',
          align: "center",
          dataIndex: 'promotionRemainAmount'
        },
        {
          title: '任务完成可用额度',
          align: "center",
          dataIndex: 'missionRemainAmount'
        },
        {
          title: '调价补差可用额度',
          align: "center",
          dataIndex: 'adjustRemainAmount'
        },
        // {
        //   title: '开始时间',
        //   width: 150,
        //   align: 'center',
        //   dataIndex: 'startTime',
        //   customRender: function (t, r, index) {
        //     return t.split(' ')[0];
        //   }
        // },
        // {
        //   title: '结束时间',
        //   width: 150,
        //   align: 'center',
        //   dataIndex: 'endTime',
        //   customRender: function(t, r, index) {
        //     return t.split(' ')[0];
        //   }
        // },
        // {
        //   title: '状态',
        //   dataIndex: 'auditStatus_dictText',
        //   align: "center"
        // }
      ],

      //操作url
      type: "checkbox",
      url: {
        list: "/stm/stmDealerDiscount/list",
        delete: "/stm/stmDealerDiscount/delete",
        deleteBatch: "/stm/stmDealerDiscount/deleteBatch",
        exportXlsUrl: "stm/stmDealerDiscount/exportXls",
        importExcelUrl: "stm/stmDealerDiscount/importExcel",
        downloadTemplate: "stm/stmDealerDiscount/download",
        discountSyncUrl: "sys/quartzJob/to-sap/updateDealerDiscount",
        getCurrentUserUrl: 'sys/userV2/getCurrentUser',
      },
      disableMixinCreated: true,

    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
    created() {
        this.getCurrentUser();
    },
  methods: {
    moment,
    clickThenCheck(record) {
      return {
        on: {
          click: () => {
            this.onSelectChange(record.id.split(","), [record]);
          }
        }
      };
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    //如果是跟单员，跟单员条件默认带出登录人姓名
    getCurrentUser() {
      let param = {};
      getAction(this.url.getCurrentUserUrl, param).then(res => {
        if (res.success && res.result.orderCheckUserFlag == 1) {
            this.queryParam.saleRealName = res.result.realname;
        }
        this.disableMixinCreated = false
            this.loadData()
        }).catch(() => {
            this.disableMixinCreated = false
            this.loadData()
        })
    },
    handleDelete: function (id) {
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    searchQuery: function () {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.loadData();
    },
    onCreateTimeChange: function (value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.startTime_begin = dateString[0]
      this.queryParam.startTime_end = dateString[1]
    },
    handleEdit: function () {
      let record = {};
      let ids = "";
      let storeIds = "";
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        for (let a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
          storeIds += this.selectionRows[a].storeId + ",";
        }
        record = this.selectionRows[0];
      }
      this.$refs.modalForm.edit(record, ids, storeIds);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleApprove: function () {
      let ids = "";
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        for (let a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
      }
      this.$refs.StmDealerInfoDiscountApprove.edit(ids);
      this.$refs.StmDealerInfoDiscountApprove.title = "审核";
      this.$refs.StmDealerInfoDiscountApprove.disableSubmit = false;
    },
    handleSync: function () {
      var that = this;
      getAction(that.url.discountSyncUrl, {jobId: 897}).then((res) => {
        if (res.success) {
          that.$message.success('折扣数据同步成功！');
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    // 复选框禁用
    getCheckboxProps(record) {
      // 加载表格的时候直接就可以拿到table所有的data数据 record是获取到表格data每一行的数据
      return {
        props: {
          // disabled里面写你要根据后台传来的值进行禁用  比方说我们的需求是(后台传来三个值分别是{1,2,3})当status 的值是1和2时禁用当前表格的复选框
          disabled: record.auditStatus === 1 ,
          // 如果代码不生效 那么就是你rowKey的问题 没有对应的唯一值 (如果不知道怎么解决 麻烦翻翻我博客园里面有解决方法)
        },
      };
    },
    downloadTemplate(fileName){
      downFile(this.url.downloadTemplate, null).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName)
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less'
</style>